﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Common.IO
{
    /// <summary>
    /// 用于文件分割和合并
    /// </summary>
    public class FileSplit
    {
        /// <summary>
        /// 分割文件
        /// </summary>
        /// <param name="fileName">需要分割的文件路径</param>
        /// <param name="blockSize">单位(M)</param>
        public void SplitFile(string fileName, int blockSize)
        {
            FileStream fsr = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            long FileLength = fsr.Length;

            int PartLength = blockSize * 1024 * 1024;
            int nCount = (int)Math.Ceiling((double)FileLength / PartLength);


            for (int i = 1; i <= nCount; i++)
            {
                byte[] byData = null;
                if (i == nCount)
                {
                    PartLength = (int)(FileLength - ((i - 1) * PartLength));
                }
                byData = new byte[PartLength];
                fsr.Read(byData, 0, byData.Length);

                FileStream fs = new FileStream(fileName + "_cd" + i, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(byData);
                bw.Close();
                byData = null;
                fsr.Flush();
                fs.Close();
            }
            fsr.Flush();
            fsr.Close();

        }
        /// <summary>
        /// 合并文件
        /// </summary>
        /// <param name="fileNames"></param>
        public void MergeFile(string[] fileNames)
        {
            foreach (string fileName in fileNames)
            {
                FileStream fsr = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                byte[] byData = new byte[fsr.Length];
                fsr.Read(byData, 0, byData.Length);
                fsr.Flush();
                fsr.Close();
                string _fileName = fileName.Substring(0, fileName.LastIndexOf("_"));
                FileStream fs = null;
                if (!System.IO.File.Exists(_fileName))
                {
                    fs = new FileStream(fileName.Substring(0, fileName.LastIndexOf("_")), FileMode.Create);
                }
                else
                {
                    fs = new FileStream(fileName.Substring(0, fileName.LastIndexOf("_")), FileMode.Append);
                }
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(byData);
                bw.Close();
                byData = null;
                fs.Close();
            }
        }
    }
}
